<template>
  <div style="width: 70%; margin-left: 15%">

    <div class="title">{{title}}</div>
    <div class="description">{{description}}</div>
    <div v-for="(question, index) in questions">
      <radio
          :isDisable="true"
          v-if="question.type === 'radio' && (question.qtype === '' || question.qtype == null)"
          :no="getno(index)"
          :question="question"
          :radio="getRadio(question)"
          @changeRadio="changeRadio"
      >
      </radio>

      <check-box
          :isDisable="true"
          v-if="question.type === 'checkbox' && (question.qtype === '' || question.qtype == null)"
          :no="getno(index)"
          :question="question"
          :checkList="getCheckBox(question)"
          @changeCheckBox="changeCheckBox"
      >
      </check-box>

      <completion
          :isDisable="true"
          v-if="question.type === 'completion'"
          :no="getno(index)"
          :question="question"
          :input="getInput(question)"
          @changeCompletion="changeCompletion"
      >
      </completion>

      <star
          :isDisable="true"
          v-if="question.type === 'score'"
          :no="getno(index)"
          :question="question"
          :max="question.options.length-1"
          :score="getScore(question)"
          @changeRadio="changeRadio"
      >
      </star>

      <radio-vote
          :isDisable="true"
          v-if="question.type === 'radio' && question.qtype ==='vote'"
          :no="getno(index)"
          :question="question"
          :radio="getRadio(question)"
          @changeRadio="changeRadio"
      >
      </radio-vote>

      <check-box-vote
          :isDisable="true"
          v-if="question.type === 'checkbox' && question.qtype === 'vote'"
          :no="getno(index)"
          :question="question"
          :checkList="getCheckBox(question)"
          @changeCheckBox="changeCheckBox"
      >
      </check-box-vote>
    </div>

  </div>
</template>

<script>
import Radio from '../question/Radio.vue'
import CheckBox from '../question/CheckBox.vue'
import Completion from '../question/Completion.vue'
import Star from '../question/Star.vue'
import RadioVote from './question/RadioVote'
import CheckBoxVote from './question/CheckBoxVote'
import axios from "axios"
import qs from "qs"
import { h } from 'vue';
import {jsonp} from 'vue-jsonp'
export default {
  name: "submit",
  components: {
    Radio,
    CheckBox,
    Completion,
    Star,
    RadioVote,
    CheckBoxVote
  },
  data() {
    return {
      id: 0,
      title: '题目',
      isPosted: false,
      description: '123456665',
      isAutoLabel: true,
      isSubmitted: false,
      questions: [],
      isSucess: false,
      isExist: true,
      type: 'base',
      randomType: '',
      result: null,
      isAutoSubmit: false,
      begin: null,
      end: null,
      date: new Date(),
      isDate: false,
      autoSubmit: false,
    }
  },
  mounted() {
    this.$message.success('提交成功')
  },
  created: function (){
    this.getAddress()
    this.getQAbaseData()
    // if (location.href.indexOf("#reloaded") === -1) {
    //   location.href = location.href + "#reloaded";
    //   location.reload();
    // }
  },
  methods: {
    isFitTime() {
      if(this.begin == null && this.end == null) {
        return false
      }
      if(Date.parse(this.begin) < this.date && Date.parse(this.end) > this.date) {
        return false
      }else{
        if (this.timer) {
          clearInterval(this.timer); // 在Vue实例销毁前，清除当前日期定时器
        };
        return true
      }
    },

    getTime() {
      let diff = (Date.parse(this.end) - this.date)
      diff = Math.floor(diff / 1000)
      const s = diff % 60
      diff = Math.floor(diff / 60)
      const m = diff % 60
      diff = Math.floor(diff / 60)
      const h = diff % 60
      diff = Math.floor(diff / 60)
      const d = diff % 24
      diff = Math.floor(diff / 60)
      return d+'天'+h+'时'+m+'分'+s+'秒'
      if(s < 0 && this.autoSubmit == false) {
        if(this.isAutoSubmit) {
          this.submit()
          this.autoSubmit = true
        }
      }
    },

    getno(index) {
      if(!this.isAutoLabel) {
        return 0
      }else{
        return index+1
      }
    },

    getdata(res) {
      return res.data.data
    },

    getRadio(question) {
      if(question.answer == null) {
        return null
      }else {
        return question.answer[0]
      }
      // if(question.optionId != null) {
      //   return question.optionId
      // }
      // question.options.forEach(option => {
      //   if(option.isDefault) {
      //     question.optionId = option.id
      //     this.changeRadio(question)
      //     return question.optionId
      //   }
      // });

    },

    getScore(question) {
      if(question.answer == null) {
        return 0
      }else {
        for(let option of question.options) {
          if(option.id == question.answer[0]) {
            return option.score
          }
        }
      }
    },

    getCheckBox(question) {
      return question.answer
      // if(question.optionIds != null) {

      //   return question.optionIds
      // }
      // question.optionIds = []
      // question.options.forEach(option => {
      //   if(option.isDefault) {
      //     question.optionIds.push(option.id)
      //   }
      // });
      // this.changeCheckBox(question)
      // return question.optionIds
    },

    getInput(question) {
      if(question.content != null) {
        return question.content
      }else{
        return ''
      }
    },

    getQuestionnaireData() {
      let data = {
        id: this.userId,
        questionnaireId: this.id,
        uuid: this.uuid,
      }
      axios.post('/api/fill/getq',qs.stringify(data)).then(res => {
        console.log(res.data.data);
        if(res.data.code == 0) {
          this.questions = this.getdata(res)['questions']
        }else {
          console.log(res)
        }
      })
    },

    getQAbaseData() {
      let data = {
        uuid: this.questionnaireId
      }
      console.log(data);
      axios.post('/api/fill/getqaInfo',qs.stringify(data)).then(res => {
        console.log(res.data);
        if(res.data.code == 0) {
          this.id = this.getdata(res)['id']
          this.title = this.getdata(res)['title']
          this.description = this.getdata(res)['description']
          this.type = this.getdata(res)['type']
          this.isAutoLabel = this.getdata(res)['isAutoLabel']
          this.isPosted = this.getdata(res)['isPosted']
          this.isNeedLogin = this.getdata(res)['isNeedLogin']
          this.randomType = this.getdata(res)['randomType']
          this.isAutoSubmit = this.getdata(res)['isAutoSubmit']
          this.begin = this.getdata(res)['beginDate']
          this.end = this.getdata(res)['endDate']
          this.isDate = this.getdata(res)['isDate']
          if(this.isDate) {
            var _this = this;
            this.timer = setInterval(() => {
              _this.date = new Date(); // 修改日期数据
            }, 1000);
          }
          this.isLogin()
          this.getIsSubmitted()
        }else if(res.data.code == -1){
          this.isExist = false
        }else {
          console.log(res)
        }
      })
    },

    getAddress() {
      let data = {
        key: 'CCYBZ-257K4-UL7UB-X4FDY-I5LNS-JMF6J',
        output: 'jsonp'
      }
      let url = "https://apis.map.qq.com/ws/location/v1/ip"
      jsonp(url, data).then(res => {
        console.log(res);
        if(res.status == 0){
          this.result = res
        }
      })
    },

    isLogin() {
      if(this.isExist && this.isPosted && this.isNeedLogin) {
        if(this.userId == null) {
          const { href } = this.$router.resolve({
            path: '/login',
          });
          window.open(href,'_blank')
          return
        }
      }
    },

    getIsSubmitted() {
      let data = {
        id: this.userId,
        questionnaireId: this.id,
        uuid: this.uuid,
      }
      console.log(data);
      axios.post('/api/fill/isSubmitted',qs.stringify(data)).then(res => {
        console.log(res);
        if(res.data.code == 0)  {
          this.isSubmitted = this.getdata(res).isSubmitted
          window.localStorage.setItem('uuid', this.getdata(res).uuid)
          this.getQuestionnaireData()
        } else
          console.log(res);
      })
    },

    // getUserData() {
    //   if(localStorage.getItem('id') != null) {
    //   let data = {
    //     id: localStorage.getItem('id'),
    //     questionnaireId: this.questionnaireId
    //   }
    //   axios.post('api/fill/getRecordData',qs.stringify(data)).then(res => {
    //     if(res.data.code === 0) {
    //       const data = this.getdata(res)
    //       console.log(data);
    //       for(let index in this.questions){
    //         switch(data[index].type){
    //           case 'radio':
    //           case 'score':
    //             this.questions[index] = Object.assign({}, this.questions[index], {optionId:data[index].optionId})
    //             break
    //           case 'checkbox':
    //             this.questions[index] = Object.assign({}, this.questions[index], {optionIds:data[index].optionIds})
    //             break
    //           case 'completion':
    //             this.questions[index] = Object.assign({}, this.questions[index], {content:data[index].content})
    //             break
    //         }
    //       }
    //     }else {
    //       console.log(res)
    //     }
    //   })

    //   }
    // },

    changeRadio(question) {
      for(let item of this.questions) {
        if(item.id == question.id && item.type == question.type) {
          item = question
          let data = {
            id: this.userId,
            questionId: question.id,
            optionId: question.answer[0],
            questionnaireId: this.id,
            uuid: this.uuid
          }
          console.log(data);
          if(question.type == 'radio')
            axios.post('/api/fill/submitRadio',qs.stringify(data)).then(res => {
              if(res.data.code == 0) {

              }else {
                console.log(res)
              }
            })
          else
            axios.post('/api/fill/submitScore',qs.stringify(data)).then(res => {
              if(res.data.code == 0) {

              }else {
                console.log(res)
              }
            })
        }
      }
    },

    changeCheckBox(question) {
      if(localStorage.getItem('id') != null && this.isSubmitted == false) {
        for(let item of this.questions) {
          if(item.id == question.id && item.type == question.type) {
            item = question
            let data = {
              id: this.userId,
              questionId: question.id,
              questionnaireId: this.id,
              uuid: this.uuid,
              options: question.answer,
            }
            console.log(data);
            axios.post('/api/fill/submitCheckBox',data).then(res => {
              if(res.data.code == 0) {

              }else {
                console.log(res)
              }
            })
          }
        }
      }
    },

    changeCompletion(question) {
      if(localStorage.getItem('id') != null && this.isSubmitted == false) {
        for(let item of this.questions) {
          if(item.id == question.id && item.type == question.type) {
            item = question
            let data = {
              id: this.userId,
              questionId: question.id,
              questionnaireId: this.id,
              uuid: this.uuid,
              content: question.content,
            }

            axios.post('/api/fill/submitCompletion', qs.stringify(data)).then(res => {
              if(res.data.code == 0) {
              }else {
                console.log(res)
              }
            })
          }
        }
      }
    },

    notSubmit(question) {
      switch(question.type) {
        case "radio":
        case 'score':
        case 'checkbox':
          if(question.answer == null){
            return false
          }else {
            return true
          }
          break
        case 'completion':
          if(question.content == null){
            return false
          }else {
            return true
          }
          break
      }
    },

    notAll() {
      this.$notify({
        title: '错误',
        message: h('i', { style: 'color: teal'}, '还有必填问题未填写')
      });
    },

    success() {
      const { href } = this.$router.resolve({
        path: '/fill/vote/submit',
        query: {
          questionnaireId: this.questionnaireId,
        }
      });
      window.open(href,'_blank')
    },

    submit() {
      for(let question of this.questions) {
        if(question.isNecessary && !this.notSubmit(question)){
          this.notAll()
          return
        }
      }
      let data = {
        id: this.userId,
        questionnaireId: this.id,
        uuid: this.uuid,
        ipBody: this.result
      }
      axios.post('/api/fill/userSubmit',data).then(res => {
        if(res.data.code === 0) {
          this.success()
        }else if(res.data.code == -1){
          this.isSubmitted = true
        }
        else {
          console.log(res)
        }
      })
    },

    getPosition() {
      this.$confirm('请求获取您的位置信息', '提示', {
        confirmButtonText: '允许',
        cancelButtonText: '拒绝',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '获取位置成功!'
        });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    }
  },
  computed:{
    questionnaireId(){
      return this.$route.query.questionnaireId
    },
    userId() {
      return parseInt(localStorage.getItem('id'))
    },
    uuid() {
      if(localStorage.getItem('uuid') == 'NaN') {
        return null
      }
      return localStorage.getItem('uuid')
    }
  }
}
</script>

<style scoped src='assets/css/fillcss/fill.css'>
</style>
